<template>
  <div class="box">
    <header class="header">
       <van-nav-bar
        title="注册"
        left-arrow
        @click-left="$router.go(-1)"
      />
    </header>
    <div class="content">
      <van-form validate-first @failed="onFailed"  @submit="onSubmit">
        <van-field
          v-model="tel"
          name="tel"
          clearable
          placeholder="输入手机号"
          :rules="[{required:true, pattern:pattern1, message: '请输入正确内容' }]"
        />
        <van-field
          v-model="password"
          name="password"
          clearable
          placeholder="请输入密码"
          :rules="[{required:true, pattern:pattern2, message: '请输入正确内容' }]"
        />
        <div style="margin: 16px;">
          <van-button round block type="info" native-type="submit">
            注册
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>
<script>
import Vue from 'vue'
import { NavBar ,Toast,Field,Button,Form  } from 'vant'
import { register } from '@/api'

Vue.use(NavBar)
Vue.use(Toast)
Vue.use(Field)
Vue.use(Button)
Vue.use(Form)
export default {
  data () {
    return {
      tel: '15196345101',
      password: '123456',
      pattern1: /^1[3456789]\d{9}$/,
      pattern2: /\d{6}/,
    }
  },
  //methods自定义函数
  methods:{
    //提示错误信息
    onFailed(errorInfo){
      Toast.fail(errorInfo.errors[0].message)
    },
    //提交注册
    onSubmit(){
      // console.log("注册")
      register ({
        tel:this.tel,
        password:this.password
      }).then(res => {
        console.log(res.data)
        //解构出code
        const { code } = res.data
        //用switch判断返回的code值
        switch (code) {
          case '10400':
            Toast('信息不完整')
            break
          case '10666':
            Toast('注册成功')
            //跳转到用户中心页面,不能用go（）返回
            this.$router.replace('/user')
            break
          case '10606':
            Toast('该手机已注册')
            break
          default:
            break
        }
      })
    }
  },
  //mounted钩子函数
  mounted() {
    
  },
}
</script>
